package cn.ibobo.lease.admin.service.impl;

import cn.ibobo.lease.admin.dao.*;
import cn.ibobo.lease.admin.service.UserCouponService;
import cn.ibobo.lease.admin.service.UserPointService;
import cn.ibobo.lease.common.base.BaseMapper;
import cn.ibobo.lease.common.base.BaseServiceImpl;
import cn.ibobo.lease.common.dto.*;
import cn.ibobo.lease.admin.service.ResLeaseService;
import cn.ibobo.lease.common.enums.ResultEnum;
import cn.ibobo.lease.common.util.DateUtil;
import cn.ibobo.lease.common.util.UuidUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 物品租赁表业务处理接口
 * @Author lililiang
 * @Date 2018-12-13 18:36:40
 */
@Service
public class ResLeaseServiceImpl extends BaseServiceImpl<ResLeaseDTO, String> implements ResLeaseService {

    private static final Log LOGGER = LogFactory.getLog(ResLeaseServiceImpl.class);

    @Autowired
    private ResLeaseMapper mapper;
    @Autowired
    private LeaseResDetailMapper leaseResDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private UserPointService userPointService;

    @Override
    protected BaseMapper<ResLeaseDTO, String> getMapper() {
        return mapper;
    }

    /**
     * 物品租赁表列表
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public List<ResLeaseDTO> list4Page(ResLeaseDTO entity, Integer pageNum, Integer... pageSize) {
        return super.list4Page(entity, pageNum, pageSize);
    }

    /**
     * 物品租赁表列表（无分页）
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public List<ResLeaseDTO> listByCondition(ResLeaseDTO entity) {
        return super.listByCondition(entity);
    }

    /**
     * 查询物品租赁表详情信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public ResLeaseDTO queryOneByPk(String id) {
        return super.queryOneByPk(id);
    }

    /**
     * 保存物品租赁表信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer save(ResLeaseDTO entity) {
        String id = entity.getId();
        if(id == null || id.length() == 0){
            entity.setId(UuidUtil.getUuid());
            return mapper.add(entity);
        }else{
            return mapper.edit(entity);
        }
    }

    /**
     * 删除物品租赁表信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer delete(String id) {
        return super.delete(id);
    }

    /**
     * @Description 物品租赁
     * @Author lililiang
     * @Date 2018/12/23 11:26
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer lease(ResLeaseDTO entityDTO) {
        //0. 根据id查询租赁记录信息
        ResLeaseDTO resLeaseDTO = mapper.queryOneByPk(entityDTO.getId());
        if(resLeaseDTO == null){
            return ResultEnum.RES_NO_EXIST.getCode();
        }
        //1. 校验租赁物品状态
        LeaseResDetailDTO leaseResDetailDTO = leaseResDetailMapper.queryOneByPk(resLeaseDTO.getDid());
        if(leaseResDetailDTO == null ){
            return ResultEnum.LEA_NO_EXIST.getCode();
        }else if(leaseResDetailDTO.getStatus() != 1 || leaseResDetailDTO.getRstatus() != 1){
            return ResultEnum.ERR_LEA_STATUS.getCode();
        }
        //2. 校验押金
        UserDTO userDTO = userMapper.queryOneByPk(resLeaseDTO.getUid());
        if(userDTO == null || userDTO.getDeposit() == null
                || userDTO.getDeposit().compareTo(leaseResDetailDTO.getDeposit()) < 0){
            return ResultEnum.NO_ENOUGH_DEPOSIT.getCode();
        }
        //3. 修改租赁记录
        entityDTO.setCreatetm(DateUtil.getNow());
        entityDTO.setDeposit(leaseResDetailDTO.getDeposit());
        entityDTO.setPrice(leaseResDetailDTO.getPrice());
        entityDTO.setStatus(1);//0 申请租赁中  1 租赁中  2 已退租  3 故障维修中
        if(mapper.edit(entityDTO) <= 0){
            return ResultEnum.FAIL.getCode();
        }
        //4. 修改租赁物品状态
        leaseResDetailDTO = new LeaseResDetailDTO();
        leaseResDetailDTO.setDid(resLeaseDTO.getDid());
        leaseResDetailDTO.setStatus(2);
        if(leaseResDetailMapper.edit(leaseResDetailDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        return ResultEnum.SUCCESS.getCode();
    }

    /**
     * @Description 物品归还
     * @Author lililiang
     * @Date 2018/12/23 11:26
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer back(ResLeaseDTO entityDTO){
        //1. 校验租赁物品信息
        ResLeaseDTO resLeaseDTO = mapper.queryOneByPk(entityDTO.getId());
        if(resLeaseDTO == null){
            return ResultEnum.NO_LEA_REC.getCode();
        }else if(resLeaseDTO.getStatus() != 1){
            return ResultEnum.ERR_USE_STATUS.getCode();
        }
        //2. 计算租赁费用-暂不校验

        //3. 修改租赁记录状态
        entityDTO.setBacktm(DateUtil.getNow());
        entityDTO.setStatus(2);
        if(mapper.edit(entityDTO) <= 0){
            return ResultEnum.FAIL.getCode();
        }
        //4. 修改租赁物品库存状态
        LeaseResDetailDTO leaseResDetailDTO = new LeaseResDetailDTO();
        leaseResDetailDTO.setDid(resLeaseDTO.getDid());
        leaseResDetailDTO.setStatus(1);
        if(leaseResDetailMapper.edit(leaseResDetailDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //5. 根据消费返还点金券比例计算返还的点金券金额
        DictDTO dict = new DictDTO();
        dict.setMasterCode("coupon_ratio");
        List<DictDTO> dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //6. 生成点金券赠送记录   修改会员点金总额
        UserCouponDTO couponDTO = new UserCouponDTO();
        couponDTO.setUid(resLeaseDTO.getUid());
        couponDTO.setMoney(entityDTO.getTotalcost()
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString()))
                .multiply(new BigDecimal("0.01")));//查询的比例为百分比，需要乘0.01
        couponDTO.setType(3); //1平台发放，2充值赠送，3租赁赠送，4线上购物赠送，5线下购物赠送 6线下购物使用
        couponDTO.setBusId(entityDTO.getId());
        if(userCouponService.coupon(couponDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //7. 根据消费返还积分比例计算返还的积分数量
        dict.setMasterCode("point_ratio");
        dictDTOS = dictMapper.listByCondition(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        //8. 生成积分赠送记录 / 修改会员当前积分/总积分
        UserPointDTO pointDTO = new UserPointDTO();
        pointDTO.setUid(resLeaseDTO.getUid());
        pointDTO.setPoint(entityDTO.getTotalcost()
                .multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString())
                        .multiply(new BigDecimal("0.01")))
                .intValue());
        pointDTO.setType((byte)3);//1 使用积分  2 充值赠送  3 租赁赠送  4线上购物赠送
        pointDTO.setBusId(entityDTO.getId());
        if (userPointService.point(pointDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        return ResultEnum.SUCCESS.getCode();
    }

    /**
     * @Description 查询租赁费用（归还前使用）
     * @Author lililiang
     * @Date 2019/2/15 20:33
     * @Param [id]
     * @Return cn.ibobo.lease.common.dto.ResLeaseDTO
     */
    @Override
    @Transactional
    public ResLeaseDTO queryCost(String id){
        ResLeaseDTO resLeaseDTO = super.queryOneByPk(id);
        //计算费用
        String createtm = resLeaseDTO.getCreatetm();
        Integer hour = DateUtil.getHour(createtm);
        if(hour < 0){
            return null;
        }
        resLeaseDTO.setLeacost(resLeaseDTO.getPrice().multiply(new BigDecimal(hour)));
        resLeaseDTO.setBacktm(DateUtil.getNow());
        resLeaseDTO.setHour(hour);
        return resLeaseDTO;
    }
}
